﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Common;
using CommonModel.Config;

namespace FilterModel
{
    /// <summary>
    /// 请求监控过滤器
    /// </summary>
    public class RequestMonitorActionFilter: ActionFilterAttribute
    {
        private const string Key = "RequestMonitor";

        /// <summary>
        /// Action执行前
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (LogConfig.IsOpenRequestMonitorLog)
            {
                Stopwatch stopWatch = new Stopwatch();
                actionContext.Request.Properties[Key] = stopWatch;
                LogHelper.Debug("请求访问Url：" + actionContext.Request.RequestUri.AbsoluteUri);
                stopWatch.Start();
            }
        }

        /// <summary>
        /// Action执行后
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (LogConfig.IsOpenRequestMonitorLog)
            {
                Stopwatch stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
                if (stopWatch != null)
                {
                    stopWatch.Stop();
                    LogHelper.Debug(string.Format(@"访问 {0} 用时 {1}ms", actionExecutedContext.Request.RequestUri.AbsoluteUri, stopWatch.Elapsed.TotalMilliseconds));
                }
            }
        }
    }
}
